package com.example.elderlycare.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.elderlycare.dao.entity.Department;
import com.example.elderlycare.dao.entity.NursingHome;
import com.example.elderlycare.dao.mapper.DepartmentMapper;
import com.example.elderlycare.dao.mapper.NursingHomeMapper;
import com.example.elderlycare.service.DepartmentService;
import com.example.elderlycare.service.entity.DepartmentTreeResponseBody;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {
    @Resource
    DepartmentMapper departmentMapper;

    @Resource
    NursingHomeMapper nursingHomeMapper;

    @Override
    public DepartmentTreeResponseBody getDepartmentTree() {
        List<DepartmentTreeResponseBody.DepartmentTreeSetItem> departmentTreeSetItem = new ArrayList<>();
        Map<String, Object> nursingHomeParams = new HashMap<>();
        List<NursingHome> nursingHomes = nursingHomeMapper.selectByMap(nursingHomeParams);
        for (NursingHome nursingHome : nursingHomes) {
            Map<String, Object> params = new HashMap<>();
            params.put("nurse_id", nursingHome.getId());
            List<Department> department = departmentMapper.selectByMap(params);
            List<DepartmentTreeResponseBody.DepartmentTreeItem> items =
                    DepartmentTreeResponseBody.generateTree(department, 0);
            departmentTreeSetItem.add(DepartmentTreeResponseBody.DepartmentTreeSetItem.builder().
                    nurseId(nursingHome.getId()).
                    nurse(nursingHome.getName()).
                    children(items).build()
            );
        }


        return DepartmentTreeResponseBody.builder().items(departmentTreeSetItem).build();
    }
}
